<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="信息名称">
                <a-input
                  v-model="queryParam.infoName"
                  placeholder="请输入信息名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="等级">
                <a-select
                  v-model="queryParam.level"
                  placeholder="请选择">
                  <a-select-option value="1">普通</a-select-option>
                  <a-select-option value="2">重要</a-select-option>
                  <a-select-option value="3">特别重要</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="状态">
                <a-select
                  v-model="queryParam.status"
                  placeholder="请选择">
                  <a-select-option value="0">禁用</a-select-option>
                  <a-select-option value="1">启用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="24">
              <span
                class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="handleAdd">新建</a-button>
      </div>
      <div>
        <a-row :gutter="48">
          <a-col
            :md="24"
            :sm="24">
            <s-table
              ref="table"
              size="default"
              rowKey="infoId"
              :columns="columns"
              :data="loadData"
              showPagination="auto"
              :customRow="tableCustomRow">
              <span
                slot="serial"
                slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span
                slot="status"
                slot-scope="text">
                <a-badge
                  :status="text | statusTypeFilter"
                  :text="text | statusFilter" />
              </span>
              <span
                slot="description"
                slot-scope="text">
                <ellipsis
                  :length="10"
                  tooltip>{{ text }}</ellipsis>
              </span>
              <span
                slot="validTime"
                slot-scope="text, record">
                {{ record.validBeginDate.split(' ')[0] }} ~ {{ record.validEndDate.split(' ')[0] }}
              </span>
              <span
                slot="createTime"
                slot-scope="text, record">
                {{ record.createTime.split(' ')[0] }}
              </span>
              <span
                slot="action"
                slot-scope="text, record">
                <template>
                  <a v-if="update" @click="handleEdit(record)">配置</a>
                  <a-divider type="vertical" />
                  <a
                    v-if="deleteBtn"
                    @click="deleteInfo(record.infoId)">删除</a>
                </template>
              </span>
            </s-table>
          </a-col>
        </a-row>
      </div>
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :allUsers="allUsers"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getInfoList, allStaff, saveInfo, updateInfo, deleteInfoReq } from '@/api/manage'
import { columns } from './config'
import CreateForm from './modules/CreateForm'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'
import { Modal } from 'ant-design-vue'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
            // 权限参数
      list: false, // 列表
      save: false, // 加
      deleteBtn: false, // 删
      update: false, // 改
      // create model
      visible: false,
      confirmLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null,
      allUsers: [],
      add: false,
      edit: false,
      info: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        return this.list && getInfoList(Object.assign({}, this.queryParam, requestParameters)).then(res => {
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      }
    }
  },
  created () {
    // 点击查看
    this.list = isInMenu(this.menu, 'ROLE_but:info:list') && isInMenu(this.menu, 'ROLE_but:info:info')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:info:save') && isInMenu(this.menu, 'ROLE_but:user:select')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:info:update') && isInMenu(this.menu, 'ROLE_but:user:select')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:info:delete')
  },
  mounted () {
    isInMenu(this.menu, 'ROLE_but:user:select') && allStaff().then(res => {
      this.allUsers = res.data
    })
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd () {
      this.visible = true
      this.add = true
      this.edit = false
    },
    deleteInfo (infoId) {
      Modal.confirm({
        title: '删除信息',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.confirmLoading = true
          deleteInfoReq({ infoId }).then(() => {
            this.$refs.table.refresh()
            this.$message.success('删除成功')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleEdit (record) {
      this.visible = true
      this.info = { ...record }
      this.add = false
      this.edit = true
      const form = this.$refs.createModal.form
      this.$nextTick(() => {
        form.setFieldsValue(
          Object.assign({}, this.info, { validDate: [this.info.validBeginDate, this.info.validEndDate] })
        )
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.infoId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.infoId
            this.staffInfo = record
          }
        }
      }
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 新增
          if (this.add) {
            const param = values
            saveInfo(
              Object.assign({}, param, {
                validBeginDate: param.validDate[0],
                validEndDate: param.validDate[1],
                validDate: undefined
              })
            ).then(res => {
              if (res.code === 0) {
                this.add = false
                form.resetFields()
                this.$refs.table.refresh()
                this.confirmLoading = false
                this.$message.success('新增成功')
                this.visible = false
              }
            })
          } else if (this.edit) {
            const param = values
            updateInfo(
              Object.assign({}, param, {
                validBeginDate: param.validDate[0],
                validEndDate: param.validDate[1],
                validDate: undefined,
                infoId: this.info.infoId
              })
            ).then(res => {
              if (res.code === 0) {
                this.add = false
                form.resetFields()
                this.$refs.table.refresh()
                this.confirmLoading = false
                this.$message.success('修改成功')
                this.visible = false
              }
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    }
  }
}
</script>
